package cn.trda.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.trda.constants.SystemConfigConstants;
import cn.trda.constants.WebConstants;
import cn.trda.pojo.Account;
import cn.trda.pojo.Keywords;
import cn.trda.pojo.Systemconfig;
import cn.trda.pojo.User;
import cn.trda.service.AccountService;
import cn.trda.service.KeywordsService;
import cn.trda.service.LogService;
import cn.trda.service.SystemConfigService;
import cn.trda.util.MySqlPageUtil;

@Controller
@RequestMapping("keywords")
public class KeyWordsController extends BaseController{
	private static final Logger logger = Logger.getLogger(KeyWordsController.class);
	@Autowired
	private KeywordsService keywordsService;
	@Autowired
	private SystemConfigService systemConfigService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private LogService logsService;
	// 财务类型
		public static final Integer AccountConfigType = 1;
		// 客户类型
		public static final Integer CustomerConfigType = 5;
		public static final Integer CardTypeConfigType = 6;
		public static final Integer ServiceConfigType = 2;
		public static final Integer ServiceYearsConfigType = 3;
		public static final Integer AppUrlConfigType = 4;
		public static final Integer YouHuiConfigType = 7;
	@RequestMapping(value="/review",method=RequestMethod.GET)
	public String to(){
		return "keywords_review";
	}
	@RequestMapping(value="/review",method=RequestMethod.POST)
	@ResponseBody
	public String to2(Keywords keywords, HttpSession session) throws Exception{
		
		System.out.println(keywords);
		// 不使用
		if(keywords.getIsuse()!=null){
				if (keywords.getIsuse() == 0) {
					keywordsService.updateKeywords(keywords);
					this.addLog(this.getSessionUser(session), "用户进行关键词状态修改，状态修改为不使用");
				}
				// 已使用
				else if (keywords.getIsuse() == 1) {
					keywordsService.updateKeywords(keywords);
					this.addLog(this.getSessionUser(session), "用户进行关键词状态修改，状态修改为已使用");
				}
		}
				// 审核中
				else if (keywords.getCheckstatus() == 1) {
					keywordsService.updateKeywords(keywords);
					this.addLog(this.getSessionUser(session), "用户进行关键词状态修改，状态修改为审核中");
				} else if (keywords.getCheckstatus() == 2) {// 审核通过
					keywordsService.tx_changeStatusToOK(keywords,this.getSessionUser(session), new Date());
				} else if (keywords.getCheckstatus() == 3) {// 审核未通过
					keywordsService.tx_changeStatusToNo(keywords,this.getSessionUser(session), new Date());
				}
		return "success";
	}
	
	@ResponseBody
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public Object pagelistbysearch(Integer page, Integer rows,
			Keywords keywords, HttpSession session) throws Exception {
		User user = this.getSessionUser(session);
		
		if (user.getRoleid() == 40L) {
			keywords.setAgentid(user.getId());
		}
		if (keywords.getKeywords() != null) {
			keywords.setSearchStr("%" + keywords.getKeywords().trim() + "%");
		}
		this.addLog(user, "用户进行关键词管理功能的搜索操作");
		Integer total = keywordsService.getCount(keywords);
		List<Keywords> keywordslist = keywordsService.getKeywordsBySearch(keywords, new MySqlPageUtil(page, rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", total);
		map.put("rows", keywordslist);
		return map;
	}
	@RequestMapping(value="/xufei/{id}",method=RequestMethod.GET)
	public String xufei(@PathVariable("id") Integer id,Keywords keywords,Model model) throws Exception{
		
		keywords = keywordsService.selectByPrimaryKey((long)id);
		// 服务类别
				Systemconfig service = new Systemconfig();
				service.setConfigtype(ServiceConfigType);
				List<Systemconfig> serviceType = systemConfigService.getSystemConfigByConfigType(service);
				model.addAttribute("serviceType", serviceType);
				
				// 服务年限
				service.setConfigtype(ServiceYearsConfigType);
				List<Systemconfig> maxyears = systemConfigService.getSystemConfigByConfigType(service);
				model.addAttribute("maxyears", maxyears.get(0));
				// 优惠类型
				service.setConfigtype(YouHuiConfigType);
				List<Systemconfig> youhuiType = systemConfigService.getSystemConfigByConfigType(service);
				model.addAttribute("youhuiType", youhuiType);

				// 代理商账号
				Account account = new Account();
				account.setUserid(keywords.getAgentid());
				account = accountService.getAccountByUserId(keywords.getAgentid());
				model.addAttribute("account", account);

				//转发关键字的id
				model.addAttribute("keywords", keywords);
				return "keywords_xufei";
		
	}
	@ResponseBody
	@RequestMapping(value = "xufei/{id}", method = RequestMethod.POST)
	public Object submitxufei(@PathVariable("id") Integer id,
			Keywords keywords, String p, HttpSession session) throws Exception {
		Account account = new Account(); // 管理员为代理商续费，应该检查该代理商当前的余额
		Keywords agentid = keywordsService.selectByPrimaryKey((long)id);
		//System.out.println(agentid);
		account.setUserid(agentid.getAgentid());
		// 查询余额
		account = accountService.getAccountByUserId(agentid.getAgentid());

		// 计算价格
		Double price = Double.parseDouble(price(p)); // 计算续费年
		// 余额不足
		if (account.getMoney().doubleValue() < price) {
			return "nomoney";
		} else {
			int xufeiYear = 0;
			String[] pa = StringUtils.split(p, "-");
			if (p.contains("youhui_")) {
				String[] youhuiId = StringUtils.split(pa[1], "_"); // 获取优惠类型id
				Long youhuiid = Long.parseLong(youhuiId[1]);
				Systemconfig youhuiType = systemConfigService.selectByPrimaryKey(youhuiid); // 获取优惠的配置值
				String[] years = StringUtils.split(youhuiType.getConfigvalue(),",");
				xufeiYear = Integer.valueOf(years[0])+ Integer.valueOf(years[1]);
			} else {
				xufeiYear = Integer.valueOf(pa[1]);
			}
			
			keywordsService.tx_keywordsXuFei(keywords, pa[0], xufeiYear, price,new Date());
			return "success";
		}
	}
	@RequestMapping(value="/price",method=RequestMethod.POST)
	@ResponseBody
	public String getPrice(String p){
		return price(p);
	}
	private String price(String p) {
		// TODO Auto-generated method stub
		if (null != p) {
			String[] prames = StringUtils.split(p, "-");
			// 服务类型id
			Long serviceTypeId = Long.valueOf(prames[0]);
			// 得到服务类型
			Systemconfig serviceType = systemConfigService
					.selectByPrimaryKey(serviceTypeId);

			// 如果是优惠的类型,优惠类型的年限由购买年限和赠送年限组成，之间用","号隔开！！
			// 如：买二赠一，"2,1"
			if (prames[1].contains("youhui_")) {
				String[] youhuiId = StringUtils.split(prames[1], "_");
				Long serviceYearsId = Long.valueOf(youhuiId[1]);
				// 得到年限配置
				Systemconfig serviceYearConfig = systemConfigService.selectByPrimaryKey(serviceYearsId);

				// 截取字符串得到购买年限和优惠年限,以“,”号分隔
				String[] discount = StringUtils.split(serviceYearConfig.getConfigvalue(), ",");

				// 计算服务价格,使用购买的年限计算
				double mul = Double.parseDouble(serviceType.getConfigvalue())* Double.parseDouble(discount[0]);
				// 返回价格
				return String.valueOf(mul);
			} else {
				double mul = Double.parseDouble(serviceType.getConfigvalue())* Double.parseDouble(prames[1]);
				return String.valueOf(mul);
			}
		}
		// 返回失败：fail
		return "fail";
	}
	
/*				陈中床-start					*/
	/**
	 * 点击导航菜单关键字申请时，加载页面处理【已测试】
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping(value="shenqing",method=RequestMethod.GET)
	public String keywordsshenqing(HttpServletRequest request) throws Exception{
		//获取登录用户信息
		User user=(User) request.getSession().getAttribute(WebConstants.SESSION_USER_KEY);
		//根据用户ID获取当前用户的账户信息
		Account account=accountService.getAccountByUserId(user.getId());
		request.setAttribute("account", account);
		//设置类型为服务类型
		List<Systemconfig> serviceType=systemConfigService.selectByConfigType(SystemConfigConstants.ServiceConfigType);
		request.setAttribute("serviceType", serviceType);
		//设置类型为查找最大服务年限
		Systemconfig maxyears=systemConfigService.selectByConfigType(SystemConfigConstants.ServiceYearsConfigType).get(0);
		request.setAttribute("maxyears", maxyears);
		//设置为查找优惠类型
		List<Systemconfig> youhuiType=systemConfigService.selectByConfigType(SystemConfigConstants.YouHuiConfigType);
		request.setAttribute("youhuiType", youhuiType);	
		return "keywords";
	}
	
	/**
	 * 检查关键字是否被注册【已测试】
	 * @param keywords
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="check",method=RequestMethod.POST)
	@ResponseBody
	public String checkkeywords(String keywords) throws Exception{
		if(keywordsService.checkKeywords(keywords)==null){
			//如果根据关键字找不到，说明还没有被注册
			return WebConstants.OPERATION_MESSAGE_SUCCESS;
		}else{
			//如果找到了，那就说明已经被注册
			return WebConstants.OPERATION_MESSAGE_FAIL;
		}		
	}

	@RequestMapping(value="manage")
	public String gotomanage(String keywords) throws Exception{
		return "keywords_manage";
	}
	
	/**
	 * 提交关键字去审核
	 * @param p
	 * @param keywords
	 * @param customId
	 * @param customName
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="submit",method=RequestMethod.POST)
	@ResponseBody
	public String submitkeywords(String p,Keywords keyword,Long customid,HttpServletRequest request) throws Exception{
		//需要提供  关键字，客户名称，代理商，申请年限，申请日期，到期日期
		//根据session获取代理商
		User agent=(User) request.getSession().getAttribute(WebConstants.SESSION_USER_KEY);
		//查看代理商账户
		Account account=accountService.getAccountByUserId(agent.getId());
		Double money=account.getMoney();
		//申请关键字需要的钱
		Double price=Double.parseDouble(getPrice(p));
		if(price>money){
			//如果代理商的账户不足以支付关键字的费用
			return WebConstants.OPERATION_MESSAGE_NOMONEY;
		}else{
			//设置代理商信息
			keyword.setAgentid(agent.getId());
			keyword.setAgentname(agent.getUsername());
			// 设置总费用
			keyword.setPrice(price);

			//获取服务年限,和服务id
			String[] str=p.split("-");
				// 获取服务类型id
				Long serviceTypeId = Long.valueOf(str[0]);
				// 根据id查询服务类型
				Systemconfig serviceTypeConfig = systemConfigService.selectByPrimaryKey(serviceTypeId);
				// 预注册冻结资金,为1年的服务费
				keyword.setPreregfrozenmoney(Double.parseDouble(serviceTypeConfig.getConfigvalue()));
				// 设置购买服务的id
				keyword.setProducttype((int)(long)serviceTypeConfig.getId());
				String years=str[1];
				Integer serviceYears;
				//对服务年限进行判断是否为优惠类型
				if(years.contains("youhui_")){
					//如果是优惠类型，传入的为youhui_id				
					 Systemconfig systemConfigYears=systemConfigService.selectByPrimaryKey(Long.parseLong(years.split("_")[1]));
					//根据获取的systemConfig获取他的Configvalue，为  "购买年限,增送年限"的格式
					String[] configvalues=systemConfigYears.getConfigvalue().split(",");
					//服务年为购买的+赠送的
					serviceYears=Integer.parseInt(configvalues[0])+Integer.parseInt(configvalues[1]);
				}else{
					//如果不是优惠的，服务年=购买年;
					serviceYears=Integer.parseInt(years);
				}
				keyword.setServiceyears(serviceYears);
				
			//如果年限不为负数
			if(keyword.getServiceyears()>0){
				//设置注册时间
				Date date=new Date();
				keyword.setPreregdatetime(date);
				keyword.setRegdatetime(date);
				//预计注册通过时间
				keyword.setRegpassdatetime(new Date(date.getTime()+(5*24*60*60*1000)));
				//到期时间=注册通过时间+服务时间
				date.setYear(date.getYear()+keyword.getServiceyears());
				keyword.setRegpassdatetime(date);
				// 设置不过期
				keyword.setIspass(0);
				// 设置为已使用
				keyword.setIsuse(1);
				// 设置为已申请
				keyword.setCheckstatus(0);
				// 对关键字进行添加，账户资金操作，...等
				keywordsService.saveKeywords(keyword, agent, date);	
				return WebConstants.OPERATION_MESSAGE_SUCCESS;
				
			}else{
				return WebConstants.OPERATION_MESSAGE_FAIL;
			}
		}
	}
	
	
	//打开开通app的页面【keywords_manage.js】
		@RequestMapping(value = "app/open/{id}", method = RequestMethod.GET)
		public String openapp(@PathVariable("id") Long id, Keywords keywords,
				Model model) throws Exception {
			//需要返回keywords,systemconfig
			keywords=keywordsService.selectByPrimaryKey(id);
			Systemconfig systemconfig=systemConfigService.selectByPrimaryKey((long)keywords.getProducttype());
			model.addAttribute("keywords", keywords);
			model.addAttribute("systemconfig", systemconfig);	
			return "open_app";
		}	
		//提交开通app【keywords_manage.js】
		@ResponseBody
		@RequestMapping(value="app/open/{id}",method=RequestMethod.POST)
		public String appOpen(@RequestParam("id") Long id,Keywords keyword,HttpServletRequest request) throws Exception{
			//需要返回keywords,systemconfig
			if(keyword.getAppusername()!=null
				&&keyword.getApppassword()!=null
				&&!keyword.getAppusername().trim().isEmpty()
				&&!keyword.getApppassword().trim().isEmpty()
			){
				//如果app账户密码不为空,设置app相关
				if(addApp(keyword)){
					return WebConstants.OPERATION_MESSAGE_SUCCESS;			
				}else{
					return WebConstants.OPERATION_MESSAGE_FAIL;
				}
			}else{
				return WebConstants.OPERATION_MESSAGE_EMPTY;
			}
		}
		/**
		 * 添加app需要操作的
		 * @return
		 */
		public boolean addApp(Keywords keywords){
			//设置appUrl
			List<Systemconfig> appUrl=systemConfigService.selectByConfigType(SystemConfigConstants.AppUrlConfigType);
			keywords.setLoginurl(appUrl.get(0).getConfigvalue());
			//设置关键字开通app
			keywords.setOpenapp(1);
			return keywordsService.updateKeywords(keywords)>0;
		} 
	/*				陈中床-end					*/
}
